using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace CapstoneMockup.Data
{
    public class Timestamps
    {
        public DateTime StartTime;

        private DateTime _endTime;

        public DateTime EndTime
        {
            get { return _endTime; }
            set
            {
                if(_endTime != value)
                {
                    _endTime = value;
                    IsFinishedTimeStamp = true;
                }
            }
        }

        public bool IsFinishedTimeStamp;

         public Timestamps()
        {
            
        }

        public Timestamps(DateTime start)
        {
            StartTime = start;
        }

        public Timestamps GetCurrentTimeStamp(ObservableCollection<Timestamps> hourslog)
        {
            if (hourslog.Count > 0)
            {
                try
                {
                    return hourslog.Last(ts => !ts.IsFinishedTimeStamp);
                }
                catch (InvalidOperationException)
                {
                }
            }
            return null;
        }

        public string TotalHoursAndMinutes(ObservableCollection<Timestamps> hoursLog)
        {
            double totalHours = 0, totalMinutes = 0;
             foreach(Timestamps ts in hoursLog)
             {
                 if(ts._endTime.DayOfWeek > 0 && ts.IsFinishedTimeStamp)
                 {
                     totalHours += CalculateHours(ts.StartTime, ts._endTime);
                     totalMinutes += CalculateMinutes(ts.StartTime, ts._endTime);
                 }
             }
            return (int)totalHours + " hours and " + (int)totalMinutes + " minutes";
        }

        //Use TimeSpan instead of calculating it by force
        private double CalculateHours(DateTime startTime, DateTime endTime)
        {
            return
                new TimeSpan(endTime.DayOfYear, endTime.Hour, endTime.Minute, endTime.Second).Subtract(
                    new TimeSpan(startTime.DayOfYear, startTime.Hour, startTime.Minute, startTime.Second)).TotalHours;
        }
        
        private double CalculateMinutes(DateTime startTime, DateTime endTime)
        {
            return
                new TimeSpan(endTime.DayOfYear, endTime.Hour, endTime.Minute, endTime.Second).Subtract(
                    new TimeSpan(startTime.DayOfYear, startTime.Hour, startTime.Minute, startTime.Second)).Minutes;
        }

        public override string ToString()
        {
            return "On " + StartTime.ToShortDateString()
                            + ": " +
                            (new Timestamps().TotalHoursAndMinutes(new ObservableCollection<Timestamps> { this}));
        }
    }
}
